# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# File       : exception_handler.py
# Time       ：2022/11/20 15:04
# Author     ：hhs
# version    ：python 3.6
# Description：
"""

import logging

from django.db import IntegrityError
from django.http import JsonResponse, Http404
from rest_framework import serializers
from rest_framework.exceptions import MethodNotAllowed

log = logging.getLogger('django')


class BusinessException(Exception):
    def __init__(self, message, data=None):
        self.message = message
        if data:
            self.data = data


def drf_exception_handler(exc, context):
    """
    处理drf框架抛出的异常，通常是在参数校验时抛出异常
    想要被drf框架的异常处理器处理，需要继承APIView
    """
    print(exc)
    log.exception(exc)
    if isinstance(exc, serializers.ValidationError):
        if exc.__str__().__contains__("username already exists"):
            return JsonResponse({"code": 400, "msg": "用户名已存在！", "data": None})
        return JsonResponse({"code": 403, "msg": "参数检验异常!", "data": None})
    if isinstance(exc, Http404):
        if exc.__str__().__contains__("No Program matches the given query"):
            return JsonResponse({"code": 400, "msg": "id不存在！", "data": None})
        return JsonResponse({"code": 400, "msg": "查询失败！", "data": None})
    if isinstance(exc, IntegrityError):
        if exc.__str__().__contains__("Duplicate entry") and exc.__str__().__contains__("username"):
            return JsonResponse({"code": 400, "msg": "用户名重复！", "data": None})
        return JsonResponse({"code": 400, "msg": "Duplicate entry", "data": None})
    if isinstance(exc, MethodNotAllowed):
        return JsonResponse({"code": 405, "msg": "请求方法不允许！", "data": None})
    if isinstance(exc, BusinessException):
        return JsonResponse({"code": 400, "msg": exc.message, "data": None})
    return JsonResponse({"code": 400, "msg": "未知异常！", "data": None})
